import Request from "@/sdk/pocky-request/index.js"; //引入
import COMM from "@/common/common.js";
import idfa from "@/js_sdk/dc-idfa/idfa.js";
/**
 * sys 系统模块,获取屏幕,系统
 */
const sys = {
    // 状态
    state: {
		sysInfo:uni.getSystemInfoSync(),
		initInfo:null,
    },
    // 内部派生
    getters: {


    },
    // 同步方法 commit
    mutations: {
		initInfo: (state, payload) => {state.initInfo = payload},
		v5Token: (state, payload) => {state.v5Token = payload},
    },
    // 异步方法 dispatch
    actions: {
		/**
		 * @description  下载文件
		 * @param {Object} url  文件url
		 */
		downloadFile(context,fileUrl){
			return new Promise((resolve,reject)=>{
				uni.downloadFile({
					url:fileUrl,
					success:(res)=>{
						if(res.statusCode==200){
							resolve(res.tempFilePath)
						}else{
							reject(res)
						}
					},
					fail:err=>{
						console.log("文件下载失败:"+err);
						reject(err);
					}
				})
			})
		},
		/**
		 * @description  根据文件路径检查文件是否存在
		 * @param {Object} filePath
		 */
		hasFile(context,filePath){
			return new Promise((resolve,reject)=>{
				uni.getSavedFileList({
					success: (res) => {
						resolve(res.fileList.find(function(file){
							return file.filePath=filePath
						}))
					},
					fail: (err) => {
						console.log("获取已下载的文件失败");
						reject(err)
					}
				})
			})
		},
		/**
		 * @description  安装更新
		 * @param {Object} filePath	更新包地址
		 */
		installUpdate(context,filePath){
			return new Promise((resolve,reject)=>{
				plus.runtime.install(filePath, {
					force: true
				}, function() { //安装成功
					resolve()
				}, function(err) { //安装失败
					console.log('安装失败:'+err);
					reject(err);
				});
			})
		},
		/**
		 * @description 存储文件
		 * @param {Object} tempFilePath
		 */
		saveFile(context,tempFilePath){
			return new Promise((resolve, reject) => {
				uni.saveFile({
					tempFilePath: tempFilePath,
					success: function(res) {
						res.tempPath=tempFilePath
						console.log("存储文件成功，存储地址：" + res);
						resolve(res);
						// res.savedFilePath   存储后的路径
					},
					fail: (err) => {
						console.log("存储文件失败:"+err);
						reject(err);
					}
				});
			})
		},
		
		
		/**
		 * @description 删除指定路径的缓存文件
		 * @param {Object} filePath 文件的路径
		 */
		removeFileByPath(context,filePath) {
			return new Promise((resolve, reject) => {
				uni.removeSavedFile({
					filePath: filePath,
					success: () => {
						resolve()
					},
					fail: (reject) => {
						reject()
					},
					complete: function(res) {
						console.log("删除文件失败:"+err);
						reject(err)
					}
				});
			})
		},
		
		// 获取下载目录缓存文件大小
		getDownloadListSize(context) {
			let downloadSize = 0;
			return new Promise(resolve => {
				uni.getSavedFileList({
					success: (res) => {
						downloadSize = res.fileList.reduce(function(x, y) {
							return Number(x) + Number(y.size)
						}, 0);
						resolve(COMM.bytesToSize(downloadSize));
					},
					fail: (err) => {
						console.log("获取下载目录文件总大小失败");
					}
				})
			})
		},
		apiGetInit(context){
			return new Promise((resolve,reject)=>{
				let _data={};
				// #ifdef APP-PLUS
				if(uni.getSystemInfoSync().platform=='ios'){
					_data.channel=10000;
				}else{
					_data.channel=plus.runtime.channel
				}
				// #endif
				// #ifdef H5
				_data.channel=10000;
				// #endif
				_data.platform=uni.getSystemInfoSync().platform.toUpperCase()
				Request().request({
					url:'/common/init.do',
					method:'post',
					data:_data
				}).then(res=>{
					if(res.data.code==1){
						uni.setStorageSync("initInfo",res.data.data)
						this.commit("initInfo",res.data.data)
						resolve(res)
					}else{
						this.commit("initInfo",uni.getStorageSync("initInfo"))
						reject(res)
					}
				}).catch(err=>{
					console.log(err);
				})
			})
		},
		/**
		 * @description 获取搜索关键词
		 * @param {Object} context
		 */
		apiGetSearchWord(context){
			return new Promise((resolve,reject)=>{
				Request().request({
					url:'/mall/hot_keys.do',
					method:'post',
					data:null
				}).then(res=>{
					if(res.data.result==1){
						resolve(res)
					}else{
			
						reject(res)
					}
				})
			})
		},
		/**
		 * @description 获取第三方登录服务供应
		 * @param {Object} context
		 */
		uniGetLoginProvider(context){
			return new Promise((resolve,reject)=>{
				uni.getProvider({
				    service: 'oauth',
				    success: res=> {
				        resolve(res)
				    },
					fail: (err) => {
						reject(err)
					}
				});
			})
		},
		/**
		 * @description 获取第三方分享服务供应
		 * @param {Object} context
		 */
		uniGetShareProvider(context){
			return new Promise((resolve,reject)=>{
				uni.getProvider({
				    service: 'share',
				    success: res=> {
				        resolve(res)
				    },
					fail: (err) => {
						reject(err)
					}
				});
			})
		},
		shareText(context,_data){
			switch (_data.provider){
				case 'WXSceneSession':{
					uni.share({
						provider: "weixin",
						scene: "WXSceneSession",
						type: 1,
						summary:_data.text,
						success: function (res) {
							
						},
						fail: function (err) {
						   
						}
					});
				}break;
				case 'WXSenceTimeline':{
					uni.share({
						provider: "weixin",
						scene: "WXSenceTimeline",
						type: 1,
						summary:_data.text,
						success: function (res) {
							
						},
						fail: function (err) {
						   
						}
					});
				}break;
				case 'QQ':{
					if (plus.os.name == 'Android') {
					    plus.runtime.launchApplication(  
					        {  
					            pname: 'com.tencent.mobileqq'  
					        },  
					        function(e) {  
					            console.log('打开QQ失败' + e.message);  
					        }  
					    );  
					} else if (plus.os.name == 'iOS') {  
					    plus.runtime.launchApplication({ action: 'mqq://' }, function(e) {  
					        console.log('打开QQ失败: ' + e.message);  
					    });  
					}  
				}break;
				case 'sinaweibo':{
					uni.share({
						provider: "sinaweibo",
						type: 1,
						summary:_data.text,
						success: function (res) {
							
						},
						fail: function (err) {
						   
						}
					});
				}break;
				default:
					break;
			}
			
		},
		/**
		 * 分享图文链接卡片
		 * @param {Object} context
		 * @param {Object} _data
		 */
		shareCard(context,_data){
			console.log(_data);
			_data.href=encodeURI(_data.href);
			switch (_data.provider){
				case 'WXSceneSession':{
					uni.share({
					    provider: "weixin",
					    scene: "WXSceneSession",
					    type: 0,
						href:_data.href,
						title:_data.title,
						summary:_data.text,
						imageUrl:_data.img,
					    // imageUrl: "https://hbimg.huabanimg.com/7d310b0a6c8fbec846cb277b4ef9b1cf5ff572cdd35e-jpl3Sx_fw658",
					    success: function (res) {
					        console.log("success:" + JSON.stringify(res));
					    },
					    fail: function (err) {
					        console.log("fail:" + JSON.stringify(err));
					    }
					});
				}break;
				case 'WXSenceTimeline':{
					uni.share({
						provider: "weixin",
						scene: "WXSenceTimeline",
						type: 0,
						title:_data.title,
						imageUrl:_data.img,
						href:_data.href,
						summary:_data.text,
						success: function (res) {
							
						},
						fail: function (err) {
						   
						}
					});
				}break;
				case 'QQ':{
						if (uni.getSystemInfoSync().platform == 'ios') {
							uni.downloadFile({
								url:_data.img,
								success: (res) => {
									console.log(res.tempFilePath);
									uni.$emit("hide");
									uni.share({
										provider: "qq",
										type: 0,
										title: _data.title,
										imageUrl: res.tempFilePath,
										href: _data.href,
										summary: _data.text,
										success: function(res) {
											uni.$emit("hide");
											console.log(res);
										},
										fail: function(err) {
											uni.$emit("hide");
											console.log(err);
										}
									});
									
								}
							})
						} else {
							uni.downloadFile({
								url:_data.img,
								success: (res) => {
									console.log(res.tempFilePath);
									uni.$emit("hide");
									uni.share({
										provider: "qq",
										type: 0,
										title: _data.title,
										imageUrl: res.tempFilePath,
										href: _data.href,
										summary: _data.text,
										success: function(res) {
											uni.$emit("hide");
											console.log(res);
										},
										fail: function(err) {
											uni.$emit("hide");
											console.log(err);
										}
									});
									
								}
							})

						}
					}break;
				case 'sinaweibo':{
						uni.downloadFile({
							url:_data.img,
							success: (res) => {
								console.log(res.tempFilePath);
								uni.$emit("hide");
								uni.share({
									provider: "sinaweibo",
									type: 0,
									title: _data.title,
									imageUrl: res.tempFilePath,
									href:_data.href,
									summary: _data.text,
									success: function(res) {
										uni.$emit("hide");
										console.log(res);
									},
									fail: function(err) {
										console.log(err);
										uni.$emit("hide");
									}
								});
								
							}
						})
						

					}break;
				default:
					break;
			}
		},
		/**
		 * 获取感兴趣内容
		 * @param {Object} context
		 */
		apiGetInterest(context){
			return new Promise((resolve, reject) => {
				Request().request({
					url: '/common/guide/list.do',
					method: 'post',
					data: {}
				}).then(res => {
					resolve(res)
				}).catch(err => {
					reject(res)
				})
			})
		},
		/**
		 * @description 日志上报
		 * @param {Object} context
		 * @param {Object} _data
		 * type:   1 课程    2店铺
		 */
		apiReporgLog(context,_data){
			// #ifdef APP-PLUS
			return new Promise((resolve, reject) => {
				let _postData={};
				// IMEI获取
				if(uni.getSystemInfoSync().platform=='android'){
					let _imei='';
					if(plus.device.imei.indexOf(',')>0){
						_imei=plus.device.imei.split(',')[0]
					}else{
						_imei=plus.device.imei
					}
					_postData.imei=_imei;
					_postData.channel=  plus.runtime.channel;
				}else{
					_postData.imei=idfa.value();
					_postData.channel= 10000;
				}
				
				// userId
				if(context.rootState.user.isLogin){
					_postData.userId=context.rootState.user.userInfo.userId
				}
				// 兴趣
				_postData.guideCate=uni.getStorageSync('xinqu').join(',')
				_postData.city=context.rootState.map.locationCity.adcode;
				_postData.version=context.rootState.upDate.nowAppInfo.version;
				_postData.pushId=plus.push.getClientInfo().clientid
				_postData.network=context.rootState.netWork.nowNetType;
				_postData.brand=context.state.sysInfo.brand;
				_postData.model=context.state.sysInfo.model;
				_postData.type=parseInt(_data.type);
				_postData.linkId=parseInt(_data.linkId);
				console.log(_postData);
				Request().request({
					url: '/common/log.do',
					method: 'post',
					data: _postData
				}).then(res => {
					console.log(res);
					resolve(res)
				}).catch(err => {
					reject(res)
				})
			})
			// #endif
			
		},
    }
}

export default sys
